﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Newtonsoft.Json;
using SW.Lite.BLL.Master;
using SW.Lite.Core.Attributes;
using SW.Lite.Core.Authority;
using SW.Lite.Infrastructure.Common;
using SW.Lite.Model.Master;

namespace SW.Lite.WebSite.Areas.Master.Controllers
{
    /// <summary>
    ///     Class RoleController.
    /// </summary>
    public class MRoleController : BaseController
    {
        /// <summary>
        ///     Indexes the specified page.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <returns>ActionResult.</returns>
        [Menu(MenuCode = "MRoleManage")]
        public ActionResult Index(int page)
        {
            var list = Role.All(page, PageSize);
            ViewBag.RecordCount = list.AllCount;
            return View(list);
        }

        /// <summary>
        ///     Adds the specified role.
        /// </summary>
        /// <param name="role">The role.</param>
        /// <returns>JsonResult.</returns>
        [Button(MenuCode = "MRoleManage", ButtonCode = "Add", IsAjax = true)]
        public JsonResult Add(RoleModel role)
        {
            var result = Role.Insert(role);
            return result
                ? new JsonResult { Data = new ExecuteResult { Result = true } }
                : new JsonResult { Data = new ExecuteResult { Result = false, Message = result.Message } };
        }

        /// <summary>
        ///     Edits the specified role.
        /// </summary>
        /// <param name="role">The role.</param>
        /// <returns>JsonResult.</returns>
        [Button(MenuCode = "MRoleManage", ButtonCode = "Edit", IsAjax = true)]
        public JsonResult Edit(RoleModel role)
        {
            var result = Role.Update(role);
            return result
                ? new JsonResult { Data = new ExecuteResult { Result = true } }
                : new JsonResult { Data = new ExecuteResult { Result = false, Message = result.Message } };
        }

        /// <summary>
        ///     Deletes the specified ids.
        /// </summary>
        /// <param name="ids">The ids.</param>
        /// <returns>JsonResult.</returns>
        [Button(MenuCode = "MRoleManage", ButtonCode = "DeleteAll", IsAjax = true)]
        public JsonResult Delete(string ids)
        {
            if (ids.Length <= 0)
                return new JsonResult { Data = new ExecuteResult { Message = "请选择删除的角色" } };

            var et = ids.Split(',').Select(n => Convert.ToInt32(n));
            var result = Role.Delete(et.ToArray());
            return result
                ? new JsonResult { Data = new ExecuteResult { Result = true } }
                : new JsonResult { Data = new ExecuteResult { Result = false, Message = result.Message } };
        }

        /// <summary>
        ///     Singles the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>JsonResult.</returns>
        [HttpPost]
        [Button(MenuCode = "MRoleManage", ButtonCode = "Add,Edit", IsAjax = true)]
        public JsonResult Single(int id)
        {
            return new JsonResult { Data = Menu.Single(id) };
        }

        /// <summary>
        ///     Roles the menu.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>ActionResult.</returns>
        [Button(MenuCode = "MRoleManage", ButtonCode = "Role")]
        public ActionResult RoleMenu(int id)
        {
            var role = Role.Single(id);
            var roleMenus = Menu.GetMenusByRoleIds(id);
            var roleButtons = Button.GetButtonsByRoleIds(id);
            var menus = Menu.All().OrderBy(n => n.Sort);

            var list = menus.Where(menu => menu.ParentID == 0)
                .OrderBy(menu => menu.Sort)
                .Select(menu =>
                {
                    var children = menus.Where(c => c.ParentID == menu.Id).OrderBy(c => c.Sort).Select(c =>
                    {
                        var buttons = Button.GetButtonsByMenuId(c.Id);
                        return new
                        {
                            MenuID = c.Id,
                            name = c.Title,
                            iconS = c.Icon,
                            @checked = roleMenus.Select(r => r.Id).Contains(c.Id),
                            children =
                                buttons == null || buttons.Count <= 0
                                    ? null
                                    : new[]
                                    {
                                        new
                                        {
                                            type = "BUTTON",
                                            name = "按钮",
                                            @checked = false,
                                            buttons = buttons.Select(b => new
                                            {
                                                name = b.Title,
                                                icon = b.Icon,
                                                id = b.Id,
                                                @checked = roleButtons.Select(rb => rb.Id).Contains(b.Id)
                                            })
                                        }
                                    },
                            open = true
                        };
                    });
                    return new
                    {
                        MenuID = menu.Id,
                        name = menu.Title,
                        @checked = roleMenus.Select(r => r.Id).Contains(menu.Id),
                        children,
                        iconS = menu.Icon,
                        open = true
                    };
                });

            ViewBag.Tree = JsonConvert.SerializeObject(list);
            return View(role);
        }

        /// <summary>
        ///     Saves the role.
        /// </summary>
        /// <param name="roleId">The role identifier.</param>
        /// <param name="jsonMenu">The json menu.</param>
        /// <param name="jsonButton">The json button.</param>
        /// <returns>JsonResult.</returns>
        [HttpPost]
        [Button(MenuCode = "MRoleManage", ButtonCode = "Role")]
        public JsonResult SaveRole(int roleId, string jsonMenu, string jsonButton)
        {
            if (!String.IsNullOrEmpty(jsonMenu))
            {
                var roleMenus = jsonMenu.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var roleMenusList = new List<int>();
                foreach (var kv in roleMenus)
                {
                    int menuId;
                    if (Int32.TryParse(kv, out menuId))
                        roleMenusList.Add(menuId);
                }

                var menuResult = Role.SaveRoleMenus(roleId, roleMenusList.ToArray());
                if (!menuResult)
                    return new JsonResult { Data = new ExecuteResult { Result = false, Message = "角色菜单保存失败" } };
            }

            if (!String.IsNullOrEmpty(jsonButton))
            {
                var roleButtons = jsonButton.Split(',');
                var roleButtonsList = new List<int>();
                foreach (var kv in roleButtons)
                {
                    int buttonId;
                    if (Int32.TryParse(kv, out buttonId))
                        roleButtonsList.Add(buttonId);
                }

                var buttonResult = Role.SaveRoleButtons(roleId, roleButtonsList.ToArray());
                if (!buttonResult)
                    return new JsonResult { Data = new ExecuteResult { Result = false, Message = "角色菜单保存失败" } };
            }

            return new JsonResult { Data = new ExecuteResult { Result = true } };
        }
    }
}